<template>
  <view class="business-trip-approval-form">
    <scroll-view class="form-container" scroll-y="true">
      <uni-card>
        <view class="form-title">{{ dialogTitle }}</view>
				
				
        
        <uni-forms ref="formRef" :model="formData" :rules="rules" label-width="80px">
          <!-- 工作单位 -->
          <uni-forms-item label="工作单位" name="department" required>
            <view class="multi-select-container">
              <view class="selected-user-tag" v-show="formData.departmentName">
                <text>{{ formData.departmentName }}</text>
              </view>
              
              <view v-if="!readonly && !isApproval" class="add-user-btn" @click="openDepartmentPopup">
                <uni-icons type="plus" size="16"></uni-icons>
                <text>选择工作单位</text>
              </view>
              
              <view>
                <uni-popup ref="departmentPopup" background-color="#fff" type="bottom">
                  <view class="tree-box">
                    <view class="popup-header">
                      <text>选择工作单位</text>
                      <uni-icons type="close" size="20" @click="closeDepartmentPopup"></uni-icons>
                    </view>
                    
                    <view class="tree-box-top">
                      <DaTree
                        :data="enabledDeptOptions"
                        labelField="label"
                        valueField="id"
                        defaultExpandAll
                        :defaultCheckedKeys="formData.department"
                        @change="handleTreeChange" />
                    </view>
                    
                    <view class="tree-box-btn">
                      <view class="popup-actions">
                        <button class="btn primary" @click="closeDepartmentPopup">确定</button>
                      </view>
                    </view>
                  </view>
                </uni-popup>
              </view>
            </view>
          </uni-forms-item>

          <!-- 日期 -->
          <uni-forms-item label="日期" name="businessTripDate" required>
            <uni-datetime-picker
              v-model="formData.businessTripDate"
              type="date"
              :disabled="readonly || isApproval"
              placeholder="请选择日期"
            ></uni-datetime-picker>
          </uni-forms-item>

          <!-- 出差人（多选） -->
          <uni-forms-item label="出差人" name="businessTripUser" required>
            <view class="multi-select-container">
              <view 
                v-for="user in selectedUsers" 
                :key="user.userId" 
                class="selected-user-tag"
              >
                <text>{{ user.nickName }}-{{ user.userName }}</text>
                <uni-icons 
                  v-if="!readonly && !isApproval" 
                  type="close" 
                  size="14" 
                  @click="removeUser(user.userId)"
                ></uni-icons>
              </view>
              
              <view v-if="!readonly && !isApproval" class="add-user-btn" @click="showUserSelector">
                <uni-icons type="plus" size="16"></uni-icons>
                <text>添加出差人</text>
              </view>
            </view>
          </uni-forms-item>

          <!-- 用户选择弹窗 -->
          <uni-popup ref="userPopup" type="bottom">
            <view class="user-selector-popup">
              <view class="popup-header">
                <text>选择出差人</text>
                <uni-icons type="close" size="20" @click="closeUserPopup"></uni-icons>
              </view>
              
              <view class="search-box">
                <uni-easyinput
                  v-model="userSearchKeyword"
                  placeholder="搜索用户"
                  @input="searchUsers"
                ></uni-easyinput>
              </view>
              
              <scroll-view class="user-list" scroll-y="true">
                <view 
                  v-for="user in filteredUsers" 
                  :key="user.userId" 
                  class="user-item"
                  :class="{ selected: isUserSelected(user.userId) }"
                  @click="toggleUserSelection(user)"
                >
                  <text>{{ user.nickName }}-{{ user.userName }}</text>
                  <uni-icons 
                    v-if="isUserSelected(user.userId)" 
                    type="checkmark" 
                    size="16" 
                    color="#409EFF"
                  ></uni-icons>
                </view>
                
                <view v-if="filteredUsers.length === 0" class="empty-users">
                  <text>暂无用户</text>
                </view>
              </scroll-view>
              
              <view class="popup-actions">
                <button class="btn primary" @click="confirmUserSelection">确定</button>
                <button class="btn default" @click="closeUserPopup">取消</button>
              </view>
            </view>
          </uni-popup>

          <!-- 审核人 -->
          <uni-forms-item label="审核人" name="reviewUser" required>
            <uni-data-select
              v-model="formData.reviewUser"
              :localdata="reviewUserOptions"
              :clear="!readonly && !isApproval"
              :disabled="readonly || isApproval"
              placeholder="请选择审核人"
            ></uni-data-select>
          </uni-forms-item>

          <!-- 出差地点 -->
          <uni-forms-item label="出差地点" name="businessTripAddress" required>
            <uni-easyinput
              v-model="formData.businessTripAddress"
              :disabled="readonly || isApproval"
              placeholder="请输入出差地点"
            ></uni-easyinput>
          </uni-forms-item>

          <!-- 出差天数 -->
          <uni-forms-item label="出差天数" name="businessTripDays" required>
            <uni-number-box
              v-model="formData.businessTripDays"
              :min="1"
              :disabled="readonly || isApproval"
            ></uni-number-box>
          </uni-forms-item>

          <!-- 出差事由 -->
          <uni-forms-item label="出差事由" name="businessTripReason" required>
            <uni-easyinput
              type="textarea"
              v-model="formData.businessTripReason"
              :disabled="readonly || isApproval"
              placeholder="请输入出差事由"
            ></uni-easyinput>
          </uni-forms-item>

          <!-- 审批部分 -->
          <template v-if="isApproval || (formData.processStatus === '2' || formData.processStatus === '3')">
            <uni-forms-item label="审批结果" name="processStatus" required>
              <uni-data-checkbox
                v-model="formData.processStatus"
                :localdata="approvalOptions"
                :disabled="readonly || !isApproval"
              ></uni-data-checkbox>
            </uni-forms-item>

            <uni-forms-item label="备注" name="remark">
              <uni-easyinput
                type="textarea"
                v-model="formData.remark"
                :disabled="readonly || !isApproval"
                placeholder="请输入备注"
              ></uni-easyinput>
            </uni-forms-item>
          </template>

          <!-- 签名部分 -->
          <template v-if="isApproval">
            <view 
              v-show="!readonly && formData.processStatus === '2'" 
              class="signature-section"
            >
              <view class="section-title">领导签字</view>
              <canvas 
                canvas-id="leaderSignaturePad" 
                class="signature-pad"
                @touchstart="onTouchStart"
                @touchmove="onTouchMove"
                @touchend="onTouchEnd"
              ></canvas>
              <view class="signature-actions">
                <button class="btn default" @click="clearLeaderSignature">清除</button>
                <button class="btn primary" @click="saveLeaderSignature">保存签名</button>
              </view>
            </view>

            <!-- 签名预览 -->
            <view 
              v-if="readonly && formData.processStatus === '2' && signatureData" 
              class="signature-preview"
            >
              <view class="section-title">签名预览</view>
              <image :src="signatureData" class="signature-image" mode="widthFix"></image>
              <view class="preview-actions">
                <button class="btn primary" @click="downloadSignature">下载签名</button>
              </view>
            </view>
          </template>
        </uni-forms>
				
				<template v-if="handle === 'edit' || readonly || isApproval">
					<ApprovalProcess :process-status="Number(formData.processStatus)" :has-reviewer="false" />
				</template>

        <!-- 操作按钮 -->
        <view class="form-actions" v-if="!readonly">
					<button class="btn default large" @click="handleClose">取消</button>
          <button class="btn primary large" @click="submitForm">提交</button>
        </view>
        
        <view class="form-actions" v-else>
          <button class="btn default large" @click="handleClose">关闭</button>
        </view>
      </uni-card>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import DaTree from '@/components/da-tree/index.vue'
import ApprovalProcess from './approvalProcess.vue'
import { 
  businessTripApprovalAdd,
  businessTripApprovalEdit,
  businessTripApprovalGet,
  businessTripApprovalSubmit
} from "@/api/documentApproval/businessTripApproval"	
import { deptTreeSelect, listUser } from "@/api/system/user"

// 响应式数据
const formData = reactive({
  id: null,
  department: null,
  departmentName: '',
  businessTripDate: '',
  businessTripUser: [],
  reviewUser: null,
  businessTripAddress: '',
  businessTripDays: 1,
  businessTripReason: '',
  processStatus: '',
  remark: '',
  leaderSignature: ''
})

const signatureData = ref(null)
const isDrawing = ref(false)
const lastX = ref(0)
const lastY = ref(0)
const ctx = ref(null)
const handle = ref('')
const isApproval = ref(false)
const readonly = ref(false)

// 部门选项
const enabledDeptOptions = ref([])

// 审批选项
const approvalOptions = ref([
  { value: '2', text: '同意' },
  { value: '3', text: '不同意' }
])

// 用户选择相关
const allUsers = ref([])
const filteredUsers = ref([])
const selectedUsers = ref([])
const tempSelectedUsers = ref([])
const userSearchKeyword = ref('')

// 审核人选项
const reviewUserOptions = ref([])

// 表单引用
const formRef = ref(null)
const userPopup = ref(null)
const departmentPopup = ref(null)

// 计算属性
const dialogTitle = computed(() => {
  if (readonly.value) return '查看出差申请'
  if (isApproval.value) return '出差审批'
  return formData.id ? '编辑出差申请' : '新增出差申请'
})

// 表单验证规则
const rules = reactive({
  department: {
    rules: [{ required: true, errorMessage: '请选择工作单位' }]
  },
  businessTripDate: {
    rules: [{ required: true, errorMessage: '请选择日期' }]
  },
  businessTripUser: {
    rules: [{ required: true, errorMessage: '请选择出差人' }]
  },
  reviewUser: {
    rules: [{ required: true, errorMessage: '请选择审核人' }]
  },
  businessTripAddress: {
    rules: [{ required: true, errorMessage: '请输入出差地点' }]
  },
  businessTripDays: {
    rules: [{ required: true, errorMessage: '请输入出差天数' }]
  },
  businessTripReason: {
    rules: [{ required: true, errorMessage: '请输入出差事由' }]
  },
  processStatus: {
    rules: [{ required: true, errorMessage: '请选择审批结果' }]
  }
})

// 部门选择相关方法
const openDepartmentPopup = () => {
  departmentPopup.value?.open()
}

const closeDepartmentPopup = () => {
  departmentPopup.value?.close()
}

const handleTreeChange = (allSelectedKeys, currentItem) => {
  console.log('handleTreeChange ==>', allSelectedKeys, currentItem)
  formData.department = allSelectedKeys
  formData.departmentName = currentItem.label
}

// 初始化画布
const initCanvas = () => {
  ctx.value = uni.createCanvasContext('leaderSignaturePad')
  ctx.value.setStrokeStyle('#000000')
  ctx.value.setLineWidth(3)
  ctx.value.setLineCap('round')
  ctx.value.setLineJoin('round')
}

// 触摸事件处理
const onTouchStart = (e) => {
  if (readonly.value) return
  const touch = e.touches[0]
  isDrawing.value = true
  lastX.value = touch.x
  lastY.value = touch.y
}

const onTouchMove = (e) => {
  if (!isDrawing.value || readonly.value) return
  const touch = e.touches[0]
  ctx.value.beginPath()
  ctx.value.moveTo(lastX.value, lastY.value)
  ctx.value.lineTo(touch.x, touch.y)
  ctx.value.stroke()
  ctx.value.draw(true)
  lastX.value = touch.x
  lastY.value = touch.y
}

const onTouchEnd = () => {
  isDrawing.value = false
}

// 签名操作
const clearLeaderSignature = () => {
  if (readonly.value) return
  ctx.value.clearRect(0, 0, 300, 150)
  ctx.value.draw(true)
}

const saveLeaderSignature = () => {
  if (readonly.value) return
  uni.canvasToTempFilePath({
    canvasId: 'leaderSignaturePad',
    success: (res) => {
      formData.leaderSignature = res.tempFilePath
      uni.showToast({ title: '签名保存成功' })
    },
    fail: (err) => {
      console.error('保存签名失败:', err)
      uni.showToast({ title: '保存签名失败', icon: 'none' })
    }
  })
}

const downloadSignature = () => {
  if (!signatureData.value) return
  uni.saveImageToPhotosAlbum({
    filePath: signatureData.value,
    success: () => {
      uni.showToast({ title: '签名已保存到相册' })
    },
    fail: () => {
      uni.showToast({ title: '保存失败', icon: 'none' })
    }
  })
}

// 用户选择相关方法
const loadAllUsers = async () => {
  try {
    let res = await listUser({ nickName: '' })
    allUsers.value = res.rows
    filteredUsers.value = [...res.rows]
  } catch (error) {
    console.error('加载用户失败:', error)
  }
}

const loadReviewUsers = async () => {
  try {
    let res = await listUser({ nickName: '' })
    reviewUserOptions.value = res.rows.map(item => {
      return {
        value: item.userId,
        text: item.nickName + '-' + item.userName
      }
    })
    console.log('reviewUserOptions', reviewUserOptions.value)
  } catch (error) {
    console.error('加载审核人失败:', error)
  }
}

// 部门树相关方法
const getDeptTree = () => {
  deptTreeSelect().then(response => {
    function normalizeDept(list) {
      return list.map(dept => {
        dept.id = String(dept.id)
        dept.label = dept.label
        if (dept.children && dept.children.length) {
          dept.children = normalizeDept(dept.children)
        }
        return dept
      })
    }
    const mapped = normalizeDept(response.data)
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(mapped)))
  })
}

const filterDisabledDept = (deptList) => {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    }
    return true
  })
}

const searchUsers = () => {
  const keyword = userSearchKeyword.value.toLowerCase()
  if (!keyword) {
    filteredUsers.value = [...allUsers.value]
    return
  }
  
  filteredUsers.value = allUsers.value.filter(user => 
    user.nickName.toLowerCase().includes(keyword) || 
    user.userName.toLowerCase().includes(keyword)
  )
}

const showUserSelector = () => {
  tempSelectedUsers.value = [...selectedUsers.value]
  userSearchKeyword.value = ''
  searchUsers()
  userPopup.value?.open()
}

const closeUserPopup = () => {
  userPopup.value?.close()
}

const isUserSelected = (userId) => {
  return tempSelectedUsers.value.some(user => user.userId === userId)
}

const toggleUserSelection = (user) => {
  const index = tempSelectedUsers.value.findIndex(u => u.userId === user.userId)
  if (index > -1) {
    tempSelectedUsers.value.splice(index, 1)
  } else {
    if (tempSelectedUsers.value.length >= 5) {
      uni.showToast({ title: '最多选择5人', icon: 'none' })
      return
    }
    tempSelectedUsers.value.push(user)
  }
}

const confirmUserSelection = () => {
  selectedUsers.value = [...tempSelectedUsers.value]
  formData.businessTripUser = selectedUsers.value.map(user => user.userId)
  closeUserPopup()
}

const removeUser = (userId) => {
  selectedUsers.value = selectedUsers.value.filter(user => user.userId !== userId)
  formData.businessTripUser = selectedUsers.value.map(user => user.userId)
}

// 加载表单数据
const loadFormData = async (id) => {
  uni.showLoading({ title: '加载中' })
  
  try {
    const res = await businessTripApprovalGet(id)
    const data = res.data
    
    Object.assign(formData, data)
    
    formData.businessTripUser = data.businessTripUsersList.map(user => user.id)
    selectedUsers.value = data.businessTripUsersList.map(user => ({
      userId: user.id,
      userName: user.name,
      nickName: user.nickName
    }))
    
    formData.reviewUser = Number(data.reviewUser)
    
    console.log('selectedUsers', selectedUsers.value)
    console.log('formData', formData)
    
    // 加载签名（如果是查看模式）
    if (readonly.value && data.leaderSignature) {
      signatureData.value = data.leaderSignature
    }
    
  } catch (error) {
    console.error('加载表单数据失败:', error)
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

// 表单提交
const submitForm = async () => {
  try {
    // 验证表单
    const valid = await formRef.value?.validate()
    if (!valid) return
    
    // 审批时需要验证签名
    if (isApproval.value && formData.processStatus === '2' && !formData.leaderSignature) {
      uni.showToast({ title: '请先保存领导签名', icon: 'none' })
      return
    }
    
    const params = {
      department: formData.department,
      businessTripDate: formData.businessTripDate,
      businessTripUser: formData.businessTripUser.join(','),
      reviewUser: formData.reviewUser,
      businessTripAddress: formData.businessTripAddress,
      businessTripDays: formData.businessTripDays,
      businessTripReason: formData.businessTripReason,
      businessTripUsersList: selectedUsers.value.map(user => ({
        id: user.userId,
        nickName: user.nickName
      }))
    }
    
    if (isApproval.value) {
      params.processStatus = formData.processStatus
      params.remark = formData.remark
      params.id = formData.id
      
      if (formData.processStatus === '2') {
        params.leaderSignature = formData.leaderSignature
      }
      
      // 调用审批API
      console.log('审批参数:', params)
      await businessTripApprovalEdit(params)
    } else {
      if (formData.id) {
        params.id = formData.id
        params.processStatus = formData.processStatus === '3' ? '0' : formData.processStatus
        // 调用编辑API
        console.log('编辑参数:', params)
        await businessTripApprovalEdit(params)
      } else {
        params.processStatus = '0'
        // 调用新增API
        console.log('新增参数:', params)
        await businessTripApprovalAdd(params)
      }
    }
    
    uni.showToast({ title: '提交成功' })
    handleClose()
    
  } catch (error) {
    console.error('表单提交失败:', error)
    uni.showToast({ title: '提交失败', icon: 'none' })
  }
}

// 关闭表单
const handleClose = () => {
  uni.navigateBack()
}

// 页面加载
onLoad((options) => {
  const getFormTitle = (handle) => {
    const titles = {
      'add': '新增出差申请',
      'edit': '编辑出差申请',
      'view': '查看出差申请',
      'approve': '出差审批'
    }
    return titles[handle] || '出差申请'
  }
  
  uni.setNavigationBarTitle({
    title: getFormTitle(options.handle)
  })
  
  handle.value = options.handle || ''
  isApproval.value = options.handle === 'approve'
  readonly.value = options.handle === 'view'
  
  loadAllUsers()
  loadReviewUsers()
  getDeptTree()
  
  if (options.id) {
    formData.id = options.id
    loadFormData(options.id)
  }
  
  nextTick(() => {
    if (isApproval.value) {
      initCanvas()
    }
  })
})
</script>

<style scoped lang="scss">
.business-trip-approval-form {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.form-container {
}

.form-title {
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.tree-box {
  display: inline-block;
  width: 100vw;
  max-height: 70vh;
  padding: 20px;
  overflow: auto;
  border-radius: 10px;
  
  .tree-box-top {
    height: 50vh;
    border: 1px solid #dcdfe6;
    border-radius: 10px;
  }
  
  .tree-box-btn {
    padding-top: 15px;
  }
}

/* 多选用户样式 */
.multi-select-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 10px;
}

.selected-user-tag {
  display: flex;
  align-items: center;
  background-color: #ecf5ff;
  color: #409EFF;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.selected-user-tag uni-icons {
  margin-left: 4px;
  cursor: pointer;
}

.add-user-btn {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  border: 1px dashed #dcdfe6;
  padding: 4px 8px;
  border-radius: 4px;
  color: #606266;
  font-size: 12px;
}

.add-user-btn uni-icons {
  margin-right: 4px;
}

/* 用户选择弹窗 */
.user-selector-popup {
  background: #fff;
  border-radius: 12px 12px 0 0;
  padding: 20px;
  max-height: 70vh;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-weight: bold;
  font-size: 16px;
}

.search-box {
  margin-bottom: 15px;
}

.user-list {
  max-height: 300px;
  margin-bottom: 15px;
}

.user-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.user-item.selected {
  background-color: #ecf5ff;
  color: #409EFF;
}

.empty-users {
  text-align: center;
  padding: 20px;
  color: #999;
}

.popup-actions {
  display: flex;
  gap: 10px;
}

/* 签名部分 */
.signature-section,
.signature-preview {
  margin: 20px 0;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

.signature-pad {
  width: 100%;
  height: 150px;
  background-color: #f5f7fa;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
}

.signature-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.signature-image {
  width: 100%;
  border: 1px solid #eee;
  border-radius: 4px;
}

.preview-actions {
  text-align: right;
  margin-top: 10px;
}

/* 操作按钮 */
.form-actions {
  display: flex;
  gap: 15px;
  margin-top: 30px;
  padding: 0 10px;
}

.btn {
  flex: 1;
  border-radius: 6px;
  font-size: 16px;
}

.btn.primary {
  background-color: #409EFF;
  color: #fff;
}

.btn.default {
  background-color: #f5f7fa;
  color: #606266;
  border: 1px solid #dcdfe6;
}

.btn.large {
  height: 44px;
  line-height: 44px;
}

:deep(.uni-forms-item__content) {
  flex-direction: column;
  align-items: flex-start;
}

:deep(.uni-forms-item__label) {
  margin-bottom: 8px;
}
</style>